<template>
  <n-page-header
    class="px-4 py-3 sticky top-0 z-10 bg-white dark:bg-[#101014]"
    title="完成打卡"
    @back="handleBack"
  >
    <template #extra>
      <n-button
        strong
        secondary
        round
        size="small"
        type="info"
        @click="show = true"
        >创建</n-button
      >
    </template>
  </n-page-header>
  <n-divider class="!m-0" />
  <div class="p-4">
    <n-collapse>
      <n-collapse-item
        v-for="(item, index) in recordCompletion"
        :key="item.id"
        :name="item.id"
      >
        <template #header>
          <n-flex>
            <span class="text-sm">
              {{ item.title }}
            </span>
            <span class="text-sm text-gray-500 select-none">
              今日已打卡{{
                item.history.find(
                  (item) => item.date === dayjs().format('YYYY-MM-DD')
                )?.data.length || 0
              }}次
            </span>
          </n-flex>
        </template>
        <template #header-extra>
          <n-flex>
            <n-button
              type="primary"
              size="small"
              @click.stop="handleComplete(item)"
            >
              打卡
            </n-button>
            <n-button type="info" size="small" @click.stop="openHistory(item)">
              记录
            </n-button>
            <n-button
              type="error"
              size="small"
              @click.stop="handleDeleteComplete(item.id)"
            >
              删除
            </n-button>
          </n-flex>
        </template>
        <div class="select-none">
          <p class="text-sm text-gray-500 mb-3">
            今日{{
              item.history.find(
                (item) => item.date === dayjs().format('YYYY-MM-DD')
              )?.data.length
                ? ''
                : '暂无'
            }}打卡记录
          </p>
          <n-flex>
            <n-tag
              v-for="(i, _index) in item.history.find(
                (item) => item.date === dayjs().format('YYYY-MM-DD')
              )?.data || []"
              :key="i.id"
              type="info"
              closable
              @close="
                deleteItem(
                  index,
                  item.history.findIndex(
                    (item) => item.date === dayjs().format('YYYY-MM-DD')
                  ),
                  _index
                )
              "
            >
              {{ dayjs(i.time).format('HH:mm:ss') }}，第{{ _index + 1 }}次打卡
            </n-tag>
          </n-flex>
        </div>
      </n-collapse-item>
    </n-collapse>
  </div>

  <Modal v-model="show" title="创建提醒">
    <template #content>
      <n-flex justify="end">
        <n-input v-model:value="title" placeholder="请输入标题" />
        <n-button type="primary" @click="handleCreate">创建</n-button>
      </n-flex>
    </template>
  </Modal>

  <Modal v-model="showHistory" title="打卡记录">
    <template #content>
      <div class="py-2">
        <n-collapse>
          <n-collapse-item
            v-for="item in historyItem.sort((a, b) =>
              b.date.localeCompare(a.date)
            )"
            :key="item.id"
            :name="item.id"
          >
            <template #header>
              <n-flex>
                <span class="text-sm">
                  {{ item.date }}
                </span>
                <span class="text-sm text-gray-500 select-none">
                  共打卡{{ item.data.length }}次
                </span>
              </n-flex>
            </template>
            <div class="select-none">
              <p class="text-sm text-gray-500 mb-3">
                {{ item.data.length ? '' : '暂无' }}打卡记录
              </p>
              <n-flex>
                <n-tag v-for="(i, _index) in item.data" :key="i.id" type="info">
                  {{ dayjs(i.time).format('HH:mm:ss') }}，第{{
                    _index + 1
                  }}次打卡
                </n-tag>
              </n-flex>
            </div>
          </n-collapse-item>
        </n-collapse>
      </div>
    </template>
  </Modal>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'
import { useDialog } from 'naive-ui'
import type { RecordCompletionType } from '@/api/interface'
import { useAppStore } from '@/stores/modules/app'
import { useNaiveUI } from '@/hooks/useNaiveUI'

const router = useRouter()
const appStore = useAppStore()
const { showMessage } = useNaiveUI()
const dialog = useDialog()

const show = ref(false)
const title = ref('')
const recordCompletion = computed(() => appStore.recordCompletion)
const showHistory = ref(false)
const historyItem = ref<RecordCompletionType['history']>([])

const handleBack = () => {
  router.back()
}

// 创建
const handleCreate = () => {
  console.log(title.value)
  if (!title.value) {
    showMessage.error('请输入标题')
    return
  }
  appStore.addRecordCompletion({
    id: Date.now(),
    title: title.value,
    history: []
  })
  show.value = false
  title.value = ''
  showMessage.success('创建成功')
}

// 打卡
const handleComplete = (item: RecordCompletionType) => {
  // 判断是否存在今日打卡记录
  const today = dayjs().format('YYYY-MM-DD')
  let todayRecordIndex = item.history.findIndex((item) => item.date === today)
  if (todayRecordIndex === -1) {
    appStore.addRecordCompletionDate(item.id)
    todayRecordIndex = item.history.findIndex((item) => item.date === today)
  }
  appStore.addRecordCompletionItem(item.id, todayRecordIndex)
  showMessage.success('打卡成功')
}

// 删除
const handleDeleteComplete = (id: number) => {
  dialog.warning({
    title: '提示',
    content: '确定删除？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      appStore.deleteRecordCompletion(id)
      showMessage.success('删除成功')
    }
  })
}

// 删除打卡记录
const deleteItem = (index: number, index2: number, index3: number) => {
  dialog.warning({
    title: '提示',
    content: '确定删除？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      appStore.deleteRecordCompletionItem(index, index2, index3)
      showMessage.success('删除成功')
    }
  })
}

// 打开打卡记录
const openHistory = (item: RecordCompletionType) => {
  historyItem.value = item.history
  showHistory.value = true
}
</script>

<style lang="scss" scoped></style>
